/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import javax.microedition.io.*;
import javax.wireless.messaging.*;
import java.io.IOException;
/**
 *
 * @author Carlos
 */
public class Sender implements Runnable {

    private static Sender inst = new Sender();
    private Sender(){
    }

    public static Sender getInstance(){
        return inst;
    }

    private String receptor=null;
    private String puerto=null;

    private String msj=null;
    private boolean enviando=false;
    private boolean envio=false;

    public void enviarMensaje(String _receptor, String _puerto, String _msj)
    {
        if(enviando) return;
        receptor = _receptor;
        puerto = _puerto;
        msj = _msj;

        Thread th = new Thread(this);
        th.start();
    }

    public boolean envioVoto(){
        return envio;
    }

    public boolean estaEnviando(){
        return enviando;
    }

    //Enviar el mensaje
    public void run(){
        enviando = true;
        envio = false;
        try{
            enviarSMS();
            envio = true;
        }catch(Exception ex){
            System.out.println("run() atrapo: ");
            ex.printStackTrace();
        }
        enviando = false;
    }

    private void enviarSMS(){
        String dir="sms://"+ receptor +":"+puerto;

        MessageConnection cnx = null;
        try{
            //Abrir la conexion del mensaje
            cnx = (MessageConnection) Connector.open(dir);
            TextMessage mensajeTxt = (TextMessage) cnx.newMessage(MessageConnection.TEXT_MESSAGE);
            mensajeTxt.setAddress(dir);
            mensajeTxt.setPayloadText(msj);
            cnx.send(mensajeTxt);
        }catch(Throwable t){
            System.out.println("Enviar atrapo: ");
            t.printStackTrace();
        }finally{
            if(cnx != null){
                try{
                    cnx.close();
                }catch(IOException ioe){
                   System.out.println("Cierre cnx atrapo: ");
                   ioe.printStackTrace();
                }
            }
        }
    }
}
